#!/bin/bash
# File: rim-loader
# Experimental rim loader.
# Copyright (c) 2010 by Radek Hnilica

# This is an experimemtal development code of RIM file loader for PDP8
# emulator.


function loadRIM() {
    declare -r file=$1		# File to read.
    declare -i byte word origin

    {

	# Skip till LEADER mark (0b1000 0000)
	while :; do
	    read -d " " byte
	    ((128 != byte)) && break
	done

	# In byte we have next byte after LEADER mark,
	# It must be an first byte of origin.

	# Read RIM data until TRAILER mark
	until ((128 & byte)); do
	    # Rim data is sequence of ORIGIN, WORD.

	    # Check ORIGIN mark
	    if ! (( $byte & 0100 )); then
		# Report Error
		printf "RIM: Error in Origin, byte=%03o, last origin=%04o\n" $byte $origin 1>&2
		return
	    fi

	    # Load Origin
	    ((origin = ($byte & 077) <<6 )) #
	    read -d " " byte; #echo "byte = $byte"
	    ((origin |= $byte))

	    # Load word
	    read -d " " byte
	    ((word = $byte << 6)) #
	    read -d " " byte;
	    ((word |= $byte))

	    # Write word to origin
	    memory_write $word $origin
	    #DEBUG# printf "RIM: %04o: %04o\n" $origin $word
	    read -d " " byte
	done

    } <<<$(od -An -w1 -v -tu1 $file)
} # loadRim()